package com.forezp.configclient.rabbitConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0  </br>
 * @ClassName ReissueTask </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 11/22/2018 3:41 PM</br>
 */
public class ReissueTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(ReissueTask.class);

    private RabbitTemplate rabbitTemplate;

    public ReissueTask(RabbitTemplate rabbitTemplate){

        this.rabbitTemplate = rabbitTemplate;

    }

    @Override

    public void run() {

        List<MessageCorrelationData> messageCorrelationDataList = new ArrayList<MessageCorrelationData>(SendFailedMessageHolder.getAll());
        logger.info("------------------获取到" + messageCorrelationDataList.size() + "条ack=false的消息，准备重发------------------");
        SendFailedMessageHolder.clear();
        int i = 1;
        for (MessageCorrelationData messageCorrelationData : messageCorrelationDataList) {
            Message message = messageCorrelationData.getMessage();
            String messageId = message.getMessageProperties().getMessageId();
            logger.info("------------------重发第" + i + "条消息，id: " + messageId + "------------------");
            i++;
            message.getMessageProperties().setMessageId(messageId + "-重发");
            rabbitTemplate.send(messageCorrelationData.getExchange(), messageCorrelationData.getRoutingKey(),
                    messageCorrelationData.getMessage(), messageCorrelationData);
        }
        logger.info("------------------重发完成------------------");
    }
}
